package com.steve.xfood.service.impl;

import com.steve.xfood.config.UpYunConifg;
import com.steve.xfood.repository.ProductInfoRepository;
import com.steve.xfood.dto.CartDTO;
import com.steve.xfood.dataobject.ProductInfo;
import com.steve.xfood.enums.ResultEnum;
import com.steve.xfood.enums.ProductStatusEnum;
import com.steve.xfood.exception.XFoodException;
import com.steve.xfood.service.ProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author steve
 * @date 2020/5/6 14:28
 */
@Service
//@CacheConfig(cacheNames = "product") //统一配置cacheNames
public class ProductInfoServiceImpl implements ProductInfoService {
    @Autowired
    private ProductInfoRepository productInfoRepository;
    @Autowired
    private UpYunConifg upYunConifg;


    @Override
//    @Cacheable(key = "123")
    public ProductInfo findById(String productId) {
        //return productInfoRepository.findOne(productId); springboot1.5
        /**
         * 查不到返回Null
         * 使用findById(orderId).get()方法会抛异常
         */
        Optional<ProductInfo> productInfoOptional = productInfoRepository.findById(productId);
//        if(productInfoOptional.isPresent()) {
//            //如果商品存在，则图片添加到又拍云
//            return productInfoOptional.get().addImageHost(upYunConifg.getImageHost());
//        }
//        return null;
        productInfoOptional.ifPresent(e -> e.addImageHost(upYunConifg.getImageHost()));
        return productInfoOptional.orElse(null);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        //根据商品状态查询
        return productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getCode()).stream()
                .map(e -> e.addImageHost(upYunConifg.getImageHost())).collect(Collectors.toList());
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        Page<ProductInfo> productInfoPage = productInfoRepository.findAll(pageable);
        //把所有商品图片传到去又拍云
        productInfoPage.getContent().stream().forEach(e -> e.addImageHost(upYunConifg.getImageHost()));
        return productInfoPage;
    }

    @Override
//    @CachePut(key = "123")//使用CachePut的话，存储的对象和返回的对象必须一致，不然会存储失败
    public ProductInfo save(ProductInfo productInfo) {
        return productInfoRepository.save(productInfo).addImageHost(upYunConifg.getImageHost());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void increaseStock(List<CartDTO> cartDTOList) {
        //遍历参数
        for (CartDTO cartDTO : cartDTOList) {
            //查询数据库商品库存
            //ProductInfo productInfo = productInfoRepository.findOne(cartDTO.getProductId()); springboot1.5
            /**
             * 查不到返回Null
             * 使用findById(orderId).get()方法会抛异常
             */
            ProductInfo productInfo = productInfoRepository.findById(cartDTO.getProductId()).orElse(null);
            if (productInfo == null) {
                //商品不存在
                throw new XFoodException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            if (productInfo.getProductStock() < 0) {
                //商品库存小于等于0，抛出异常
                throw new XFoodException(ResultEnum.PRODUCT_STOCK_ERROR_DB);
            }
            //增加库存
            Integer stockNum = productInfo.getProductStock() + cartDTO.getProductQuantity();
            //新库存数量存入数据库
            productInfo.setProductStock(stockNum);
            productInfoRepository.save(productInfo);
        }


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void decreaseStock(List<CartDTO> cartDTOList) {
        //遍历参数
        for (CartDTO cartDTO : cartDTOList) {
            //查询数据库商品库存
            //ProductInfo productInfo = productInfoRepository.findOne(cartDTO.getProductId()); springboot 1.5
            /**
             * 查不到返回Null
             * 使用findById(orderId).get()方法会抛异常
             */
            ProductInfo productInfo = productInfoRepository.findById(cartDTO.getProductId()).orElse(null);
            if (productInfo == null) {
                //商品不存在
                throw new XFoodException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            if (productInfo.getProductStock() < 0) {
                //商品库存小于等于0，抛出异常
                throw new XFoodException(ResultEnum.PRODUCT_STOCK_ERROR_DB);
            }
            //减少库存
            Integer stockNum = productInfo.getProductStock() - cartDTO.getProductQuantity();
            if (stockNum < 0) {
                //新库存数量小于0
                throw new XFoodException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            //新库存数量存入数据库
            productInfo.setProductStock(stockNum);
            productInfoRepository.save(productInfo);
        }


    }

    @Override
    public ProductInfo onSale(String productId) {
        //ProductInfo productInfo = productInfoRepository.findOne(productId); springboot 1.5
        /**
         * 查不到返回Null
         * 使用findById(orderId).get()方法会抛异常
         */
        ProductInfo productInfo = productInfoRepository.findById(productId).orElse(null);
        if (productInfo == null) {
            throw new XFoodException(ResultEnum.PRODUCT_NOT_EXIST);
        }
        //如果商品为上架状态
        if (productInfo.getProductStatusEnum() == (ProductStatusEnum.UP) ) {
            throw new XFoodException(ResultEnum.PRODUCT_STATUS_ERROR);
        }
        //商品状态设置为下架状态
        productInfo.setProductStatus(ProductStatusEnum.UP.getCode());
        //保存到数据库
        return productInfoRepository.save(productInfo);
    }

    @Override
    public ProductInfo offSale(String productId) {
        //ProductInfo productInfo = productInfoRepository.findOne(productId); springboot 1.5
        /**
         * 查不到返回Null
         * 使用findById(orderId).get()方法会抛异常
         */
        ProductInfo productInfo = productInfoRepository.findById(productId).orElse(null);
        if (productInfo == null) {
            throw new XFoodException(ResultEnum.PRODUCT_NOT_EXIST);
        }
        //如果商品为上架状态
        if (productInfo.getProductStatusEnum() == (ProductStatusEnum.DOWN) ) {
            throw new XFoodException(ResultEnum.PRODUCT_STATUS_ERROR);
        }
        //商品状态设置为下架状态
        productInfo.setProductStatus(ProductStatusEnum.DOWN.getCode());
        //保存到数据库
        return productInfoRepository.save(productInfo);
    }
}
